<template>
  <el-dialog :title="uploadTitle" :visible="isShow" @click="closeShow()"
             width="30%">

    <!--    <div class="upload-excel">-->
    <el-form class="edit-class" label-width="80px" :model="editForm" :rules="rulesEdit" ref="edit">
      <el-form-item label="文件" prop="fileUrl">
        <el-upload
          ref="upload"
          :drag="drag"
          :auto-upload="autoUpload"
          class="upload-demo"
          :multiple="multiple"
          action="#"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :before-upload="beforeUpload"
          :accept="accept"
          :http-request="UploadFile"
          :limit="limit"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <template v-if="!drag">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传{{ accept }}文件，且不超过{{ maxSize }}M</div>
          </template>
          <template v-if="drag">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传{{ accept }}文件，且不超过{{ maxSize }}M</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <!--    </div>-->

    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="closeDialog('edit')">取消</el-button>
      <el-button size="small" type="primary" class="title" @click="submit('edit')">提交</el-button>
    </div>

  </el-dialog>
</template>
<script>
export default {
  name: 'UploadFile', // 上传组件
  props: {
    // 弹框start
    isShow: Boolean,
    // 更新报表上传接口
    upLoadRequest: {
      type: String,
      default: ''
    },
    // 弹框end
    // 上传多文件数量
    limit: {
      type: Number,
      default: 3
    },
    // 是否上传多文件
    multiple: {
      type: Boolean,
      default: false
    },
    // 是否启用拖拽上传
    drag: {
      type: Boolean,
      default: false
    },
    // 接受上传的文件类型
    accept: {
      type: String,
      default: '.xlsx,.xls,.doc,.docx'
    },
    // 上传名称
    uploadTitle: {
      type: String,
      default: '导入excel表格'
    },
    // 最大上传兆数
    maxSize: {
      type: Number,
      default: 20,
    },
    // 是否在选取文件后立即进行上传
    autoUpload: {
      type: Boolean,
      default: true
    },
  },
  data() {
    return {
      fileList: [],
      urlList: [],
      allowRequest: true,
      // 弹框start
      editForm: {
        file: '',
        fileUrl: '',
      },
      rulesEdit: {
        fileUrl: [{ required: true, message: '请上传文件', trigger: 'blur' }]
      }
      // 弹框end
    }
  },
  watch: {
    fileList: {
      handler() {
        // console.log('000')
        this.$emit('fileList', this.fileList)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 弹框start
    closeShow() {
      this.$parent.isShow = false;
    },
    resetForm(formName) {
      const vm = this
      if(!vm.$refs[formName]) return
      vm.$refs[formName].resetFields();
      vm.clearFiles();
    },
    closeDialog(formName) {
      const vm = this
      if(vm.urlList&&vm.urlList.length>0){
        vm.urlList.forEach((item)=>{
          vm.uploadDelete(item.f_url);
        })
      }
      let fromObj = {
        'edit': vm.resetForm(formName),
      }
      for(let path in fromObj){
        if(formName.indexOf(path) != -1){
          fromObj[path]
          break
        }
      }
      vm.closeShow()
    },
    // 提交方法
    submit(editData) {
      const vm = this
      vm.$refs[editData].validate(valid => {
        if (valid) {
          vm.openFullScreen()
          vm.apiUrl[vm.upLoadRequest](vm.editForm,"POST").then(res => {
            vm.closeFullScreen(this.openFullScreen())
            // console.log('res',res)
            const { code, msg } = res
            if (code == 0) {
              vm.closeShow()
              vm.showMessageMin({
                message: '提交成功！',
                type: 'success'
              })
              this.$emit('uploadRequestSuccess')
            } else {
              vm.showMessageMin({
                message: msg,
                type: 'error'
              })
            }
          })
            .catch(err => {
              vm.closeFullScreen(this.openFullScreen())
              console.log('err',err)
              if(err&&err.isCancel) return
              vm.closeShow()
              vm.showMessageMin({
                message: err.msg || '失败，请稍后再试！',
                type: 'error'
              })
            })
        } else {
          return false
        }
      })
    },
    // 弹框end
    // 清空已上传的文件列表
    clearFiles(){
      const vm = this
      vm.$refs.upload.clearFiles();
      vm.clearFileList()
      vm.getUrlList(vm.fileList, '', true)
    },
    // 上传的时候 我需要做一些什么是
    async UploadFile(file) {
      // 系统上传方法处理
      // console.log('file', file)
      const vm = this
      // console.log('vm.allowRequest', vm.allowRequest)
      if(!vm.allowRequest) return

      let Flag =
        this.fileList &&
        this.fileList.some(item => {
          if (file.file.name === item.name) {
            this.$message.error('文件名称重复')
            return true
          }
        })
      if (!Flag) {
        this.fileList.push(file.file)
      } else {
        this.fileList = this.fileList.slice(0, this.fileList.length)
      }
      // 处理数据
      let uploadData = new FormData();
      // FormData传参用append()
      uploadData.append('filename', file.filename||file.name);
      for (let i = 0; i < vm.fileList.length; i++) {
        uploadData.append('file', vm.fileList[i]);
      }
      vm.upload.uploadFile(uploadData).then((res)=>{
        vm.closeFullScreen(vm.openFullScreen());
        // console.log('res', res)
        const  { code, data, msg } = res
        if(code == 0){
          vm.editForm = {
            ...data,
            fileUrl: data.f_url
          }
          vm.urlList = vm.urlList.concat([{
            ...data,
            fileUrl: data.f_url
          }])
          // vm.$emit('getUrlList', vm.urlList)
          // this.$emit('uploadSuccess',data)
        } else {
          this.handleRemove(file.file)
          vm.showMessageMin({
            message: msg,
            type: 'error'
          })
        }
      })
    },
    // 获取选中列表
    getUrlList(arr, filename, clear=false){
      const vm = this
      if(!clear){
        vm.urlList = arr.filter(item=>item.filename != filename)
      } else {
        vm.urlList = []
      }
      // vm.$emit('getUrlList', vm.urlList)
    },

    beforeUpload(file) {
      const vm = this
      vm.openFullScreen()
      // console.log('检查大小 格式',file)
      // 图片大小限制
      if(file.size/(1024*1024)>vm.maxSize){
        vm.closeFullScreen(vm.openFullScreen());
        vm.showMessageMin({
          message: '上传文件应小于'+vm.maxSize+'M',
          type: 'error'
        })
        vm.allowRequest = false
        vm.clearFiles();
        return;
      }
      //    上传类型判断
      const imgName = file.name;
      const idx = imgName.lastIndexOf(".");
      if (idx != -1) {
        let ext = imgName.substr(idx + 1).toUpperCase();
        ext = ext.toLowerCase();
        // console.log('includes',vm.accept.split(',').includes('.'+ext))
        // const allow = vm.accept.split(',').includes('.'+ext)
        const allow = vm.accept.replaceAll(' ','').split(',').includes('.'+ext)
        if (!allow) {
          vm.closeFullScreen(vm.openFullScreen());
          vm.showMessageMin({
            message: `只能上传${vm.accept}文件`,
            type: 'error'
          })
          vm.allowRequest = false
          vm.clearFiles();
          return;
        }
      }
      vm.allowRequest = true
    },
    // 文件移除
    handleRemove(file, fileList) {
        this.uploadDelete(file)
      // this.fileList = this.fileList.filter(item => {
      //   return item.uid != file.uid
      // })
    },
    uploadDelete(fileUrl){
      const vm = this
      const f_url = fileUrl ? fileUrl : vm.editForm.f_url
      vm.openFullScreen();
      vm.apiUrl.uploadDelete({
        file: f_url
      },"POST")
        .then(res => {
          vm.closeFullScreen(vm.openFullScreen());
          const { code,msg } = res;
          if (code != 0) {
            vm.showMessageMin({
              type: 'error',
              message: msg
            })
          } else {
            vm.showMessageMin({
              type: 'success',
              message: '文件已删除！'
            })
            this.fileList = this.fileList.filter(item => {
              return item.uid != file.uid
            })
            vm.getUrlList(vm.urlList, file.name)
          }
        })
    },
    handlePreview(file) {
      // console.log(file, 'handlePreview')
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    clearFileList() {
      this.fileList = []
    }
  }
}
</script>
<style lang="less" scoped>
::v-deep .el-upload__tip {
  margin-top: -7px !important;
  margin-right: 30px !important;
}
// 弹框start
.upload-excel {
  display: flex;
  justify-content: center;
  // margin-top: 100px;
  .excel-upload-input {
    display: none;
    z-index: -9999;
  }
  .btn-upload,
  .drop {
    border: 1px dashed #bbb;
    width: 350px;
    height: 160px;
    text-align: center;
    line-height: 160px;
  }
  .drop {
    line-height: 20px;
    color: #bbb;
    i {
      font-size: 60px;
      display: block;
    }
  }
}
// 弹框end
</style>
